package com.fishery.quartz.task;

import com.alibaba.fastjson.JSON;
import org.quartz.Job;
import org.quartz.JobDataMap;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.*;
import org.springframework.web.client.RestTemplate;

import java.net.URI;
import java.util.Map;


/**
 * 任务
 */
public class ExecuteTask implements Job {

	@Autowired
	private RestTemplate restTemplate;

	@Value("${fishery.request.url.prefix}")
	private String INVOKE_URL_PREFIX;

	@Override
	public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException {
		// 获取数据集
		JobDataMap jobDataMap = jobExecutionContext.getJobDetail().getJobDataMap();
		// 获取请求方式
		String requestMethod = (String) jobDataMap.get("requestMethod");
		// 获取请求URI
		String requestUri = (String) jobDataMap.get("requestUri");
		// 获取请求体
		Map<String, Object> requestBody = JSON.parseObject((String) jobDataMap.get("requestBody"));
		// 匹配请求类型
		if ("GET".equalsIgnoreCase(requestMethod)) {
			// GET请求
			restTemplate.getForObject(INVOKE_URL_PREFIX + requestUri, String.class);
		} else if ("POST".equalsIgnoreCase(requestMethod)) {
			// POST请求
			restTemplate.postForObject(INVOKE_URL_PREFIX + requestUri, requestBody, String.class);
		} else if ("PUT".equalsIgnoreCase(requestMethod)) {
			// PUT请求
			restTemplate.put(INVOKE_URL_PREFIX + requestUri, requestBody);
		} else if ("DELETE".equalsIgnoreCase(requestMethod)) {
			// DELTE请求
			HttpHeaders headers = new HttpHeaders();
			headers.setContentType(MediaType.APPLICATION_JSON);
			RequestEntity requestEntity = new RequestEntity(requestBody, headers,
					HttpMethod.DELETE, URI.create(INVOKE_URL_PREFIX + requestUri));
			restTemplate.exchange(requestEntity, String.class);
		}
	}
}
